package com.feihao.zhou.aop;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.TransactionException;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.interceptor.DefaultTransactionAttribute;

import javax.sql.DataSource;

//@Aspect
public class TransferAdvice {


    private DataSource dataSource;

    public void setDataSource(DataSource dataSource) {
        this.dataSource = dataSource;
    }

    @Pointcut("execution(* com.feihao.zhou.service.impl.AccountServiceImpl.*(..))")
    public void pc(){}

    @Around("pc()")
    public Object around(ProceedingJoinPoint pjp) throws Throwable {

        DataSourceTransactionManager dtm = null;
        TransactionStatus transaction = null;


        Object proceed = null;
        try {
            dtm = new DataSourceTransactionManager(dataSource);
            transaction = dtm.getTransaction(new DefaultTransactionAttribute());
            //原始业务原始
            proceed = pjp.proceed();

            //提交事务
            dtm.commit(transaction);
        } catch (Throwable throwable) {
            throwable.printStackTrace();
            dtm.rollback(transaction);
        }



        //事务回滚
         return proceed;



    }
}
